<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>XMLHttpRequest2.0文件上传</title>
</head>
<body>
<form action="">
    <label>
        头像: <input type="file">
    </label>
    <label>
        <input type="button" value="保存">
    </label>
</form>
<img src="" class="preview" alt="">

<script>
    var btn = document.querySelector("input[type=button]");
    btn.onclick = function(){
        //获取文件上传表单
        var file = document.querySelector("input[type=file]");

        //console.log(file.files);

        //利用FormData实现
        var formData = new FormData(file);

        //追加数据
        formData.append("picture",file.files[0]);

        var xhq = new XMLHttpRequest();

        //监听文件上传进度
        xhq.upload.onprogress = function (ev) {
           // console.log(111);
           // console.log(ev);
            console.log((ev.loaded / ev.total) * 100 + "%");
        }

        xhq.open("post","05.php");
        xhq.send(formData);
        xhq.onreadystatechange = function () {
            if(xhq.readyState == 4 && xhq.status == 200){
                console.log(xhq.responseText);
                //document.querySelector(".preview").src = xhq.responseText;
            }
        }
    }
</script>
</body>
</html>